package org.compiere.process;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import org.compiere.model.Mhrmcheckoff;
import org.compiere.model.Mhrmcheckoffline;
import org.compiere.model.Mhrmtax;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import extend.org.compiere.utils.Util;

public class GenerateCheckOff extends SvrProcess {

	private Timestamp dateFrom;
	double SUM = .0;
	BigDecimal amount = null;
	double rate = .0;
	Calendar cMonth = Calendar.getInstance();
	
	private Mhrmcheckoff chkoff = null;
	private Mhrmcheckoffline chkoffline = null;
			
	@Override
	protected void prepare() {
		chkoff = new Mhrmcheckoff(getCtx(), getRecord_ID(), null);
	}

	@Override
	protected String doIt() throws Exception {
		
		if(chkoff.getReversal_ID() != 0)
			return null;
		else if(chkoff.get_ID() == 0)
			return null;
		
		dateFrom = chkoff.getStartDate();
		int Month = Util.getMonth(chkoff.getStartDate(), chkoff.getEndDate());
			for (int i = 0; i <= Month; i++){
				cMonth.setTime(dateFrom);
				//
				chkoffline = Mhrmcheckoffline.getCheckoffline(chkoff.getC_BPartner_ID(), dateFrom);
				if(chkoffline == null)
					chkoffline = new Mhrmcheckoffline(getCtx(),0,get_TrxName());
				chkoffline.sethrm_checkoff_ID(chkoff.gethrm_checkoff_ID());
				chkoffline.setC_BPartner_ID(chkoff.getC_BPartner_ID());
				chkoffline.setC_BPartnerRelation_ID(chkoff.getC_BPartnerRelation_ID());
				String d1 = Util.getMonthName(dateFrom, Env.getAD_Language(getCtx()), false);
				chkoffline.setDateContract(d1 + " " + cMonth.get(Calendar.YEAR) + " г. ");
				// get amount salary 
				amount =  Mhrmtax.getTotal(chkoff.getC_BPartner_ID(), dateFrom);				
				if (amount == null){
					SUM = chkoffline.gethrm_amountsalary().doubleValue();
				}else{
					SUM = amount.doubleValue();	
				}
				
				if (chkoff.gethrm_percent() != 0){
					SUM = SUM * chkoff.gethrm_percent() * 0.01;					
				}else if (chkoff.gethrm_total() != null && chkoff.gethrm_percent() == 0){
					SUM =  chkoff.gethrm_total().doubleValue();					 
				}else{
					SUM = .0;				
				}
				
				chkoffline.setDateFrom(dateFrom);
				chkoffline.sethrm_amountsalary(amount);				
				chkoffline.sethrm_percent(chkoff.gethrm_percent());
				chkoffline.sethrm_amount(chkoff.gethrm_total());
				rate = SUM * chkoff.getCommission() * 0.01;
				chkoffline.setCommission(new BigDecimal(rate));
				rate = SUM * chkoff.gethrm_postage() * 0.01;
				chkoffline.sethrm_postage(new BigDecimal(rate));				
				SUM = SUM + chkoffline.getCommission().doubleValue() + chkoffline.gethrm_postage().doubleValue(); 
				chkoffline.sethrm_total(new BigDecimal(SUM));
				chkoffline.setProcessed(true);
				chkoffline.saveEx();
				cMonth.add(Calendar.MONTH, 1);
				dateFrom = new Timestamp(cMonth.getTimeInMillis());
			}
			
			return Msg.translate(Env.getCtx(), "Success");		
	}

}
